package com.jiedeng.util;

import com.jiedeng.model.FileRecord;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

/**
 * httpclient下载报表 系列操作
 * <p>
 * Created by zhouyb on 2017/7/17.
 */
public class HttpClientDownReport {
    /**
     * 删除指定文件夹下 指定格式的文件
     *
     * @param filePath   需删除的文件夹
     * @param fileSuffix 删除类型集合
     */
    public static void deleteDirectory(String filePath, List<String> fileSuffix) {
        File file = new File(filePath);
        boolean isDirectory = file.isDirectory();
        if (isDirectory) {
            String[] files = file.list();
            for (String path : files) {
                String afterPointLetter = path.substring(path.lastIndexOf(".") + 1, path.length());
                if (forbidFormat(afterPointLetter, fileSuffix)) {
                    System.out.println(filePath + path);
                    File deleteFile = new File(filePath + "/" + path);
                    if (deleteFile.exists()) {
                        deleteFile.delete();
                    }
                }
            }
        } else {
            if (file.isFile()) {
                file.delete();
            }
        }
    }

    /**
     * 判断文件是否是指定文件类型
     *
     * @param threeLetter 文件后缀
     * @param fileSuffix  指定类型集合 如jpg xls doc
     * @return
     */
    public static boolean forbidFormat(String threeLetter, List<String> fileSuffix) {
        if (fileSuffix.contains(threeLetter)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 循环请求下载所文件 并返回目录
     *
     * @param cptLoadPath 请求前置路径
     * @param fileDownZipPath 下载文件路径
     * @param reportManageList 报表集合
     * @return
     */
    public static String getReportFromToFR(String cptLoadPath, String fileDownZipPath, List<FileRecord> reportManageList) throws IOException {
        String destFileName = null;
            String userId = SessionUtil.getUserIdSession();

            UUID uuId = UUID.randomUUID();
            destFileName = fileDownZipPath + "/" + userId + "/" + uuId + "/";
            for(FileRecord fileRecord : reportManageList) {
               //拼接请求url
                String url = cptLoadPath + fileRecord.getOldPhotoPath();
                getReportFromFile(url, destFileName +  fileRecord.getOldPhotoPath());
            }
        return destFileName;
    }

    /**
     * httpClient将文件下载指定位置
     *
     * @param url          http://www.xxx.com/img/333.jpg
     * @param destFileName xxx.jpg/xxx.png/xxx.txt
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static void getReportFromFile(String url, String destFileName)
            throws ClientProtocolException, IOException {
        // 生成一个httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        InputStream in = entity.getContent();
        File file = new File(destFileName);
        try {
            if (!file.exists()) {
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            FileOutputStream fout = new FileOutputStream(file);
            int l = -1;
            byte[] tmp = new byte[1024];
            while ((l = in.read(tmp)) != -1) {
                fout.write(tmp, 0, l);
                // 注意这里如果用OutputStream.write(buff)的话，图片会失真，大家可以试试
            }
            fout.flush();
            fout.close();
        } finally {
            // 关闭低层流。
            in.close();
        }
        httpclient.close();
    }
}
